package com.lxq.web.servlet;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.lxq.common.DaoFactory;
import com.lxq.dao.UserDao;
import com.lxq.entity.User;
import com.lxq.web.servlet.common.BaseServlet;

@WebServlet("/app/register")
public class RegisterServlet extends BaseServlet {

	private static final long serialVersionUID = 1833657034691802184L;
	private UserDao userDao = DaoFactory.getInstance("userDao", UserDao.class);

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		
		
		User user = userDao.findByPhone(phone);
		JSONObject json = new JSONObject();

		try {
			if (user == null) {
				User newUser = new User();
				Pattern p = Pattern.compile("[1][3458]\\d{9}");
				Matcher m = p.matcher(phone);
				if (!m.matches()) {
					json.put("success", false);

					json.put("reason", "手机号码不合法！");
				} else {
					Pattern p2 = Pattern.compile("\\d{4,}");
					Matcher m2 = p2.matcher(password);
					if (!m2.matches()) {
						json.put("success", false);
						json.put("reason", "密码至少4位以上！");
					} else {
						newUser.setUserId(userDao.count()+1);
						newUser.setUserName(username);
						newUser.setPassword(password);
						newUser.setPhoneNumber(phone);
						userDao.save(newUser);
						json.put("success", true);
					}
				}

			} else {
				json.put("success", false);
				json.put("reason", "该手机号已注册，尝试登陆！");
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();
	}
	
}
